package com.d3.d3xmpp.util;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.content.Context;


public class AsyncHttpUtil {
	private static Logger log = Logger.getAnonymousLogger();
    private static final String SERVER_URL = "http://192.168.0.103:8080";
    private static final String CONTENT_TYPE = "application/json";
	private static AsyncHttpClient client = new AsyncHttpClient();
	
	static {
		client.setLoggingEnabled(true);
		client.setLoggingLevel(3);
		client.addHeader(AsyncHttpClient.HEADER_CONTENT_TYPE, CONTENT_TYPE);
	}
	
	public static void get(String serviceName, Map<String, String> params, JsonHttpResponseHandler responseHandler) {
	      client.get(getAbsoluteUrl(serviceName), new RequestParams(params), responseHandler);
	  }  
	  
	  public static void post(String serviceName, Map<String, Object> params, Context context, JsonHttpResponseHandler responseHandler) {
		try {
			String content = JsonUtil.obj2Json(params);
			HttpEntity entity = new StringEntity(content);
			client.post(context, getAbsoluteUrl(serviceName), entity, CONTENT_TYPE, responseHandler);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	  }
	  
	  private static String getAbsoluteUrl(String relativeUrl) { 
	      return SERVER_URL + relativeUrl;  
	  } 

}
